package com.Work;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Exam01 {
    private final Lock letterLock = new ReentrantLock();
    private final Lock digitLock = new ReentrantLock();
    public synchronized void isLetter(String str) {
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)){
                letterLock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + ch);
                } finally {
                    letterLock.unlock();
                }
            }
        }
    }

    private synchronized void isDigit(String str) {
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                digitLock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + ch);
                } finally {
                    digitLock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        Exam01 exam01 = new Exam01();
        String str = "rew151gr5ee4y5r51h";
        Thread thread1 = new Thread(() -> {
            exam01.isLetter(str);
        }, "字母：");
        Thread thread2 = new Thread(() -> {
            exam01.isDigit(str);
        }, "数字:");

//        thread1.start();
//        thread2.start();
        Object obj = new Object();
        Thread thread3 = new Thread(() -> {
            synchronized (obj) {
                for (int i = 0; i < 26; i++) {
                    System.out.println((char) ('a' + i));
                    obj.notify();
                    try {
                        if (i < 25) {
                            obj.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread thread4 = new Thread(() -> {
            synchronized (obj) {
                for (int i = 0; i < 26; i++) {
                    System.out.println(i + 1);
                    obj.notify();
                    try {
                        if (i < 25) {
                            obj.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread3.start();
        thread4.start();
    }
}
